package org.example.api;

import org.example.dao.ImageDao;
import org.example.model.ImageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;


@WebServlet("/imageShow")
public class ImageShowServlet extends HttpServlet {

    // 防盗链
    private static final List<String> WHITE_LIST = Arrays.asList(
            "http://localhost:8080/java_image_server/",
            "http://localhost:8080/java_image_server/img_list.html",
            "http://159.75.251.133:8080/java_image_server/",
            "http://159.75.251.133:8080/java_image_server/img_list.html"
    );

    //获取图片内容接口
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String referer = req.getHeader("Referer");
        if (!WHITE_LIST.contains(referer)) {
            resp.setStatus(403);
            return;
        }
        String imageId = req.getParameter("imageId");
        ImageInfo imageInfo = ImageDao.selectOne(Integer.parseInt(imageId));
        String path = ImageServlet.LOCAL_PATH_PREFIX+imageInfo.getPath();
        //读取方式：通过FileInputStream文件输入字节流来读取
        //通过byte[] b = Files.readAllBytes(path) 工具方法 读取
        // Path对象，可以通过File对象转换
        File pic =  new File(path);
        byte[] data = Files.readAllBytes(pic.toPath());
        // 把二进制数据，写入到相应正文
        resp.getOutputStream().write(data);
    }
}
